package com.bdth.bdthiss.jsoup;

import com.bdth.bdthiss.util.MD5Utils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

/**
 * Officemate网站商品解析
 * Created by Administrator on 2020/4/3.
 */
public class OfficemateTools {
    /**
     * 根据url下载商品图片
     * @param uid 商品编码
     * @param url 商品网络地址
     * @param saveWhere 保存的位置
     * @return
     * 例如 url = http://www.officemate.cn/product-391327.html
     *      uid = 391327
     *      saveWhere = "C:\\jsoup\\images\\"
     */
    public static Map<String,String> getHtmlAndDownPic(String uid, String url, String saveWhere) throws Exception{
        Map<String, String> result = new HashMap<>();
        String type = "";
        String brand = "";
        //获取url的文档
        Document document = JsoupTools.getDocument(url);
        //第一步：下载商品的展示图片thumbnail
        FileTools.createDir(saveWhere+uid+"\\thumbnail\\");
        Elements thumbnails = document.select("div[class='thumbnail']");
        File picsn = new File(saveWhere+uid+"\\thumbnail\\picsn.txt");
        picsn.createNewFile();
        Writer picsnWriter = new FileWriter(picsn);
        for(Element thumbnail : thumbnails){
            String src = thumbnail.select("a").attr("href");
            //下载展示图片
            String fileName = FileTools.downPic(src,saveWhere+uid+"\\thumbnail");
            String fileMD5 = MD5Utils.getFileMD5String(new File(saveWhere+uid+"\\thumbnail\\"+fileName));
            String value = fileMD5+","+"upload/"+uid+"/thumbnail/"+fileName+"\r\n";
            picsnWriter.append(value);
        }
        picsnWriter.close();
        //第二步：下载商品详细内容
        //搜索到商品详情内容
        Elements detail = JsoupTools.getElement(document,"id","product_detail").getElementsByClass("detail-content").select("textarea");
        //获取第一个节点
        Element d = detail.get(0);
        //获取textarea中的值
        String value = detail.text();
        //将textarea中的值组装成文档
        Document docDetail = Jsoup.parse(value);
        Element div = docDetail.body();
        //删除文档中不需要下载的图片
        //div.select("img[alt='产品信息']").remove();
        //div.select("img[alt='产品展示']").remove();
        //获取文档中需要下载的图片
        Elements es = div.getElementsByTag("img");
        int imgCount = 0;
        for(Element e: es){
            String imgSrc = e.attr("src");
            //删除文档中不需要下载的图片
            if(imgCount == 0 || imgCount == 2) {
                div.select("img[src='" + imgSrc + "']").remove();
                imgCount++;
                continue;
            }
            //下载图片
            FileTools.downPic(FileTools.getRealUrl(imgSrc),saveWhere+uid);
            //保存为新的网络路径
            String newSrc = "/upload/images/"+uid+"/"+FileTools.getFileName(imgSrc);
            //替换当前img的src为新的网络路径
            div.select("img[src='"+imgSrc+"']").attr("src",newSrc);
            imgCount++;
        }
        String resultHtml = div.html();
        result.put("html",resultHtml);
        //第三步获取商品的类型和品牌
        Elements otherdetail = JsoupTools.getElement(document,"id","product_detail").select("ul[class='clearfix']");
        Element otherul = otherdetail.get(0);
        String ultxt = otherul.text();
        String[] li = ultxt.split(" ");
        for(String l:li){
            if(l!=null&& !"".equals(l)) {
                String[] tp = l.split("：");
                if (tp.length == 2) {
                    if (tp[0].equals("品牌"))
                        brand = tp[1];
                    if (tp[0].equals("所属分类") || tp[0].equals("分类"))
                        type = tp[1];
                }
            }
        }
        //商品类型
        result.put("type", type);
        //商品品牌
        result.put("brand", brand);
        return result;
    }

    public static void main(String[] args) throws Exception {
        String url = "http://www.officemate.cn/product-254423.html";
        String uid = "254423";
        String saveWhere = "F:\\2019\\www.bdthmall.cn\\upload\\";
        Map<String,String> result = OfficemateTools.getHtmlAndDownPic(uid,url,saveWhere);
        System.out.println(result);
    }
}
